package com.yzg.simple.netty.chat.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @ClassName NettyChatServer
 * @Description TODO
 * @Authoe weiyan
 * @Date 2019/12/30 10:33
 * @Version 1.0
 *
 * Netty 组成聊天室 ， 多方广播通讯
 **/
public class NettyChatServer {


    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup  = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();


            serverBootstrap
                    .group(bossGroup,workerGroup)
                    //设置线程连接个数
                    .option(ChannelOption.SO_BACKLOG,128)
                    .channel(NioServerSocketChannel.class)
                    // 连接处于活动状态
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new NettyChatInitializer());
            ChannelFuture channelFuture = serverBootstrap.bind(6863).sync();

            //添加监听器
            channelFuture.addListener(future -> {
                if (channelFuture.isSuccess()) {
                    System.out.println("服务器启动成功！连接为：tcp://"+channelFuture.channel().localAddress());
                }

            });

            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

        }

    }
}